﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace Common
{
    public static class PublicClass
    {
        public static bool HasFile(this HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0) ? true : false;
        }

        /// <summary>
        /// 验证文件类型
        /// </summary>
        /// <param name="file">上传上来的文件</param>
        /// <returns></returns>
        public static Boolean IsAllowedExtension(this HttpPostedFileBase file)
        {
            int fileLen = file.ContentLength;
            byte[] imgArray = new byte[fileLen];
            file.InputStream.Read(imgArray, 0, fileLen);
            MemoryStream ms = new MemoryStream(imgArray);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = br.ReadByte();
                fileclass = buffer.ToString();
                buffer = br.ReadByte();
                fileclass += buffer.ToString();
            }
            catch
            {
            }
            finally
            {
                br.Close();
                ms.Close();
            }
            //说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
            if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780")
                return true;
            else
                return false;
        }
        /// <summary>
        /// 获取图片缩略图
        /// </summary>
        /// <param name="pPath">图片路径</param>
        /// <param name="pSavePath">保存路径</param>
        /// <param name="pWidth">缩略图宽度</param>
        /// <param name="pHeight">缩略图高度</param>
        /// <param name="pFormat">保存格式，通常可以是jpeg</param>
        public static void GetSmaller(string pPath, string pSavedPath, int pWidth, int pHeight)
        {
            try
            {
                Image smallerImg;
                Image originalImg = Image.FromFile(pPath);
                Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                smallerImg = originalImg.GetThumbnailImage(pWidth, pHeight, callback, IntPtr.Zero);
                smallerImg.Save(pSavedPath, ImageFormat.Jpeg);
            }
            catch (Exception x)
            {
                //
            }
        }

        public static bool ThumbnailCallback()
        {
            return false;
        }
    
    
    }
}